import u299 from '@/assets/img/document/u299.png';
import u304 from '@/assets/img/document/u304.png';
import u309 from '@/assets/img/document/u309.png';
import DocumentDisplay from '@/pages/basicConfiguration/components/DocumentDisplay';
import {
  getBasicSettingsByUserId,
  updateBasicSetting,
} from '@/services/backend/basicSettingsController';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProDescriptions } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Divider, Flex, Form, Input, message, Space, Typography } from 'antd';
import { CSSProperties, useEffect, useRef, useState } from 'react';

// 添加统一的样式
const descriptionStyle: CSSProperties = {
  width: '100%',
  marginBottom: 24,
};

const labelStyle: CSSProperties = {
  width: '180px',
  justifyContent: 'flex-end',
  minHeight: '32px',
};
const contentStyle: CSSProperties = {
  minHeight: '32px',
  display: 'flex',
  alignItems: 'center',
};

const BasicConfiguration: React.FC = () => {
  const [u299Visible, setu299Visible] = useState<boolean>(false);
  const [u304Visible, setu304Visible] = useState<boolean>(false);
  const [u309Visible, setu309Visible] = useState<boolean>(false);
  const [departmentDto, setDepartmentDto] = useState<API.DepartmentDto>({});
  //联系人List
  const [contactsList, setContactsList] = useState<API.Contacts[]>([]);

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const ref = useRef<ActionType>();

  //返回
  const handleBack = () => {
    history.back();
  };

  //保存更新
  const update = async () => {
    try {
      const res = await updateBasicSetting({
        ...departmentDto,
      });
      if (res.code === 200) {
        ref?.current?.reload();
        message.success('更新成功');
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  //保存field
  const saveField = async (key: any, record: any) => {
    console.log(record);
    setDepartmentDto({
      ...departmentDto,
      ...record,
    });
    return true;
  };
  // 添加一个状态来跟踪数据是否已加载
  const [dataLoaded, setDataLoaded] = useState(false);

  const loadBasicInfo = async () => {
    try {
      const res = await getBasicSettingsByUserId({
        //@ts-ignore
        userId: currentUser.id,
      });
      console.log(res.data);
      setDepartmentDto(res.data ?? {});
      setContactsList(res?.data?.contactsList || []);
      // 标记数据已加载
      setDataLoaded(true);
    } catch (e: any) {
      message.error(e.message);
    }
  };

  useEffect(() => {
    //加载基本信息
    const init = async () => {
      await loadBasicInfo();
    };
    init();
  }, []);

  return (
    <PageContainer title={'基础配置'}>
      <Typography>
        <ul>
          <li>在处理案件时，将使用以下信息，生成必要的文书材料，请谨慎填写。</li>
          <li>在案件处理完成后，系统将按照以下将案件材料归档到选择的目录下。</li>
        </ul>
      </Typography>
      <ProDescriptions
        actionRef={ref}
        style={descriptionStyle}
        labelStyle={labelStyle}
        contentStyle={contentStyle}
        column={1}
        title="基本信息"
        bordered={true}
        dataSource={departmentDto}
        editable={{
          onSave: saveField,
        }}
      >
        <ProDescriptions.Item label="用户账号" dataIndex={['user', 'username']} editable={false} />
        <ProDescriptions.Item
          label={
            <>
              营业所名称<span style={{ color: '#ff4d4f' }}>*</span>
            </>
          }
          dataIndex={'name'}
          formItemProps={{
            rules: [
              { required: true, message: '请输入营业所名称' },
              {
                max: 20,
                message: '营业所名称20个字符长度，超过不允许输入',
              },
            ],
          }}
        />
        <ProDescriptions.Item
          label={
            <>
              营业所编码<span style={{ color: '#ff4d4f' }}>*</span>
            </>
          }
          dataIndex={'code'}
          formItemProps={{
            rules: [
              { required: true, message: '请输入营业所编码' },
              {
                max: 20,
                message: '营业所编码20个字符长度，超过不允许输入',
              },
            ],
          }}
        />
      </ProDescriptions>

      <ProDescriptions
        style={descriptionStyle}
        labelStyle={labelStyle}
        contentStyle={contentStyle}
        column={1}
        title="联络信息"
        editable={{
          onSave: saveField,
        }}
      >
        {dataLoaded && ( // 只有在数据加载完成后才渲染表单
          <Form
            name="dynamic_form_nest_item"
            onValuesChange={(changedValues, allValues) => {
              console.log('表单值变化', allValues.contactsList);
              setDepartmentDto({
                ...departmentDto,
                contactsList: allValues.contactsList,
              });
              setContactsList(allValues.contactsList);
            }}
            initialValues={{ contactsList: contactsList }} // 直接使用 contactsList 作为初始值
            autoComplete="off"
          >
            <Form.List name="contactsList" initialValue={[{}]}>
              {/* 移除数组括号 */}
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        label={'联系人'}
                        {...restField}
                        name={[name, 'name']}
                        rules={[{ required: true, message: '不能为空' }]}
                      >
                        <Input placeholder="请输入联系人" />
                      </Form.Item>
                      <Form.Item
                        label={'联系电话'}
                        {...restField}
                        name={[name, 'phone']}
                        rules={[{ required: true, message: '不能为空' }]}
                      >
                        <Input placeholder="请输入联系电话" />
                      </Form.Item>
                      <CloseOutlined
                        onClick={() => {
                          //获取当前的List
                          //若只有一个,则不能再删除
                          if (contactsList.length <= 1) {
                            message.warning('请至少保留1个联系人');
                            return;
                          }
                          //否则,可以删除
                          remove(name);
                        }}
                      />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      新增联系人
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form>
        )}
      </ProDescriptions>

      <ProDescriptions
        style={descriptionStyle}
        column={1}
        title="立案审批表固定文本配置"
        bordered={true}
        labelStyle={labelStyle}
        contentStyle={contentStyle}
        editable={{
          onSave: saveField,
        }}
      >
        <ProDescriptions.Item
          label={
            <>
              不予立案时<span style={{ color: '#ff4d4f' }}>*</span>
            </>
          }
          valueType="text"
          editable={false}
          fieldProps={{
            placeholder: '违反相关法律规定的口头描述',
          }}
        >
          <div>
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <div>违反相关法律规定的口头描述</div>
              <Button
                type={'link'}
                onClick={() => {
                  setu299Visible(true);
                }}
              >
                查看实例
              </Button>
            </div>
            <ProDescriptions
              column={1}
              dataSource={departmentDto}
              editable={{
                onSave: saveField,
              }}
            >
              <ProDescriptions.Item
                valueType={'textarea'}
                dataIndex={'notRegisteredDesc'}
                formItemProps={{
                  style: { width: '600px' },
                  rules: [
                    { required: true, message: '请输入相关法律条款描述。' },
                    { max: 1000, message: '法律条款描述1000个字符长度，超过不允许输入。' },
                  ],
                }}
              />
            </ProDescriptions>
          </div>
        </ProDescriptions.Item>
        <ProDescriptions.Item
          label={
            <>
              建议立案时<span style={{ color: '#ff4d4f' }}>*</span>
            </>
          }
          valueType="text"
          editable={false}
          fieldProps={{
            placeholder: '违反相关法律规定的固定文案描述',
          }}
        >
          <div>
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <div>违反相关法律规定的固定文案描述</div>
              <Button
                type={'link'}
                onClick={() => {
                  setu304Visible(true);
                }}
              >
                查看实例
              </Button>
            </div>
            <ProDescriptions
              column={1}
              dataSource={departmentDto}
              editable={{
                onSave: saveField,
              }}
            >
              <ProDescriptions.Item
                valueType={'textarea'}
                dataIndex={'notRegisteredTerm'}
                formItemProps={{
                  style: { width: '600px' },
                  rules: [
                    { required: true, message: '请输入相关法律条款描述。' },
                    { max: 1000, message: '法律条款描述1000个字符长度，超过不允许输入。' },
                  ],
                }}
              />
            </ProDescriptions>
          </div>
          <Divider />
          <div>
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <div>违法行为符合相关行政规定和法律法规，及相关描述</div>
              <Button
                type={'link'}
                onClick={() => {
                  setu309Visible(true);
                }}
              >
                查看实例
              </Button>
            </div>
            <ProDescriptions
              column={1}
              dataSource={departmentDto}
              editable={{
                onSave: saveField,
              }}
            >
              <ProDescriptions.Item
                valueType={'textarea'}
                dataIndex={'registeredTerm'}
                formItemProps={{
                  style: { width: '600px' },
                  rules: [
                    { required: true, message: '请输入相关法律条款描述。' },
                    { max: 1000, message: '法律条款描述1000个字符长度，超过不允许输入。' },
                  ],
                }}
              />
            </ProDescriptions>
          </div>
        </ProDescriptions.Item>
      </ProDescriptions>
      <ProDescriptions
        column={1}
        title="案件归档"
        bordered={true}
        style={descriptionStyle}
        labelStyle={labelStyle}
        contentStyle={contentStyle}
        dataSource={departmentDto}
        editable={{
          onSave: saveField,
        }}
      >
        <ProDescriptions.Item
          label={
            <>
              归档目录<span style={{ color: '#ff4d4f' }}>*</span>
            </>
          }
          dataIndex={'caseFiling'}
          formItemProps={{
            rules: [
              { required: true, message: '请输入归档目录' },
              {
                max: 100,
                message: '归档目录100个字符长度，超过不允许输入',
              },
            ],
          }}
        />
      </ProDescriptions>
      <Flex gap={'middle'} justify={'flex-end'}>
        <Button onClick={handleBack}>返回</Button>
        <Button type="primary" onClick={update}>
          保存
        </Button>
      </Flex>
      <DocumentDisplay src={u299} visible={u299Visible} onVisibleChange={setu299Visible} />
      <DocumentDisplay src={u304} visible={u304Visible} onVisibleChange={setu304Visible} />
      <DocumentDisplay src={u309} visible={u309Visible} onVisibleChange={setu309Visible} />
    </PageContainer>
  );
};

export default BasicConfiguration;
